package com.kma.summer2012.client.presenters.manager;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.kma.summer2012.client.CrumbsEventBus;
import com.kma.summer2012.client.events.manager.ManageWorksEvent;
import com.kma.summer2012.client.presenters.Presenter;
import com.kma.summer2012.client.services.AbstractCallBack;
import com.kma.summer2012.client.services.CrumbsCatalogOfTools.CrumbsCatalogOfToolsService;
import com.kma.summer2012.client.services.catalogOfWorks.CrumbsCatalogOfWorksService;
import com.kma.summer2012.client.services.session.CrumbsSessionService;
import com.kma.summer2012.shared.model.UICrumbsToolItem;
import com.kma.summer2012.shared.model.UICrumbsWorkItem;

import java.util.*;


public class AddWorkPresenter implements Presenter {
    public interface Display {

        void setPageTitle(String title);

        String getWorkName();

        void setWorkName(String workName);

        String getWorkDescription();

        void setWorkDescription(String workDescription);

        String getRunTime();

        void setRunTime(String runTime);

        List<String> getSelectedToolsList();

        void setSelectedToolsList(List<String> list);

        void setToolsList(List<String> list);

        ///
        String getSelectedCategory();

        ///
        void setCategoryList(List<String> categories);

        public int getSelectedParent();

        public void setSelectedParent(int category);

        HasClickHandlers getSaveButton();

        HasClickHandlers getCancelButton();

        public void setCategoryList(Map<Integer, String> list);

        Widget asWidget();

    }

    private final Display display;
    private UICrumbsWorkItem item;
    private List<UICrumbsToolItem> tools = new ArrayList<UICrumbsToolItem>();
    final Map<Integer, String> categoryList = new HashMap<Integer, String>();

    public AddWorkPresenter(Display display) {
        this.display = display;
        bind();
        //Виведення списку тулзів
        CrumbsCatalogOfToolsService.App.getInstance().getAllTools(new AbstractCallBack<List<UICrumbsToolItem>>() {
            @Override
            public void onSuccess(List<UICrumbsToolItem> uiCrumbsToolItems) {
                tools = uiCrumbsToolItems;
                List<String> namesOfTools = new ArrayList<String>();
                for (UICrumbsToolItem item : tools) {
                    namesOfTools.add(item.getToolName());

                }
                AddWorkPresenter.this.display.setToolsList(namesOfTools);
                CrumbsSessionService.App.getInstance().getParameterWorkItem("workItem", new AbstractCallBack<UICrumbsWorkItem>() {
                    @Override
                    public void onSuccess(UICrumbsWorkItem uiCrumbsWorkItem) {
                        item = uiCrumbsWorkItem;
                        fillInfo();
                    }
                });
            }
        });
    }


    private void fillInfo() {

        //Виведення інформації про заявку(якщо вона не новостворена - для едіт ворк!
        try {
            if (item.getId() != 0) {
                display.setPageTitle("Edit work");
                display.setWorkName(this.item.getWorkName());
                display.setRunTime(this.item.getRuntime().toString());
                display.setWorkDescription(this.item.getWorkDescription());
                display.setSelectedToolsList(this.item.getToolList());
            }
            //else display.setPageTitle("Add work");
        } catch (Exception e) {
            e.printStackTrace();
            Window.alert("AddWork Presenter can't open received workItem");
        }

        CrumbsCatalogOfWorksService.App.getInstance().getAllCategories(new AbstractCallBack<List<String>>() {
            @Override
            public void onSuccess(List<String> strings) {
                categoryList.put(0, "");
                for (int i = 0; i < strings.size(); i++) {
                    if (item.getWorkName() != strings.get(i)) {
                        categoryList.put(i + 1, strings.get(i));
                    }
                }
                display.setCategoryList(categoryList);
                if (item.getParentId() != 0) {
                    CrumbsCatalogOfWorksService.App.getInstance().getWorkById(item.getParentId(), new AbstractCallBack<UICrumbsWorkItem>() {
                        @Override
                        public void onSuccess(UICrumbsWorkItem uiCrumbsWorkItem) {
                            for (int key : categoryList.keySet()) {
                                if (categoryList.get(key) == uiCrumbsWorkItem.getWorkName()) {
                                    display.setSelectedParent(key);
                                }
                            }
                        }
                    });
                }
            }
        });
    }

    private void bind() {
        this.display.getSaveButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doSaveWork();
            }
        });
        this.display.getCancelButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                CrumbsEventBus.getInstance().fireEvent(new ManageWorksEvent());
            }
        });
    }

    private void doSaveWork() {
        //В презентер вже має передаватись екземпляр ЮАйВорк із принайні перентАйДі!

        if (!validation())
            return;

        item.setWorkName(this.display.getWorkName());
        item.setWorkDescription(this.display.getWorkDescription());
        item.setRuntime(Integer.parseInt(this.display.getRunTime()));
        item.setToolList(this.display.getSelectedToolsList());
        //List<UICrumbsWorkItem> workList = new ArrayList<UICrumbsWorkItem>();

        CrumbsCatalogOfWorksService.App.getInstance().getAllWorks(new AbstractCallBack<Set<UICrumbsWorkItem>>() {
            @Override
            public void onSuccess(Set<UICrumbsWorkItem> uiCrumbsWorkItems) {
                int patentId = 0;
                boolean add = true;
                String parentName = categoryList.get(display.getSelectedParent());
                for (UICrumbsWorkItem uiWork : uiCrumbsWorkItems) {
                    if (item.getWorkName().equals(uiWork.getWorkName()) && !item.isDelete() && item.getId() != uiWork.getId()) {
                        add = false;
                    }
                    if (uiWork.getWorkName().equals(parentName)) {
                        patentId = uiWork.getId();
                    }
                }
                item.setParentId(patentId);
                item.setParent(false);
                //edit
                if (add) {
                    CrumbsCatalogOfWorksService.App.getInstance().saveWorkItem(item, new AbstractCallBack<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            AddWorkPresenter.this.display.setWorkName("");
                            AddWorkPresenter.this.display.setWorkDescription("");
                            AddWorkPresenter.this.display.setRunTime("");
                            AddWorkPresenter.this.display.setToolsList(new ArrayList<String>());
                            CrumbsEventBus.getInstance().fireEvent(new ManageWorksEvent());
                        }
                    });
                } else {
                    Window.alert("Work with such name is already exist, please choose another name");
                }
            }
        });


    }

    protected boolean validation() {
        String alert = "";

        if (isInteger(this.display.getRunTime())) {
            if ((Integer.parseInt(this.display.getRunTime())) <= 0) {
                alert = ("Invalid runTime. Please enter amount of time needed in minutes");
            }
        } else alert = ("Invalid runTime. Please enter amount of time needed in minutes");

        if (this.display.getWorkName().equals("")) {
            alert = ("Please, enter work name");
        }

        if (categoryList.get(this.display.getSelectedParent()).equals("")) {
            alert = ("Please, choose category");
        }

        if (!alert.equals("")) {
            Window.alert(alert);
            return false;
        }
        return true;
    }

    public static boolean isInteger(String s) {
        try {
            Integer.parseInt(s);
        } catch (NumberFormatException e) {
            return false;
        }
        return true;
    }

    @Override
    public void go(HasWidgets container) {
        container.clear();
        container.add(display.asWidget());
    }
}
